package com.itmk.web.user_repair.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.user_repair.entity.UserRepair;
import com.itmk.web.user_repair.entity.UserRepairParm;
import com.itmk.web.user_repair.service.UserRepairService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 维修管理模块
 */
@RestController
@RequestMapping("/api/userRepair")
public class UserRepairController {
    private static final Logger logger = LoggerFactory.getLogger(UserRepairController.class);

    @Autowired
    private UserRepairService userRepairService;

    /**
     * 我的报修列表
     */
    @GetMapping("/myList")
    public ResultVo getMyList(UserRepairParm userRepairParm) {
        QueryWrapper<UserRepair> query = new QueryWrapper<>();
        query.lambda().eq(UserRepair::getUserId, userRepairParm.getUserId())
                .like(UserRepair::getRepairContent, userRepairParm.getRepairContent())
                .like(UserRepair::getStatus, userRepairParm.getStatus())
                .between(userRepairParm.getStartTime() != null && userRepairParm.getEndTime() != null,
                        UserRepair::getCommitTime, userRepairParm.getStartTime(), userRepairParm.getEndTime())
                .orderByDesc(UserRepair::getCommitTime);
        IPage<UserRepair> page = new Page<>();
        page.setSize(userRepairParm.getPageSize());
        page.setCurrent(userRepairParm.getCurrentPage());
        IPage<UserRepair> list = userRepairService.page(page, query);
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 报修列表(物业管理部人员)
     */
    @GetMapping("/list")
    public ResultVo getList(UserRepairParm userRepairParm) {
        QueryWrapper<UserRepair> query = new QueryWrapper<>();
        query.lambda().like(UserRepair::getRepairContent, userRepairParm.getRepairContent())
                .like(UserRepair::getStatus, userRepairParm.getStatus())
                .orderByDesc(UserRepair::getCommitTime);
        IPage<UserRepair> page = new Page<>();
        page.setSize(userRepairParm.getPageSize());
        page.setCurrent(userRepairParm.getCurrentPage());
        IPage<UserRepair> list = userRepairService.page(page, query);
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 新增
     */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:myRepair:add')")
    public ResultVo add(@RequestBody UserRepair userRepair) {
        userRepair.setCommitTime(new Date());
        userRepair.setStatus("0");
        boolean b = userRepairService.save(userRepair);
        if (b) {
            logger.info("新增报修记录成功，报修ID：{}", userRepair.getRepairId());
            return ResultUtils.success("报修成功!");
        }
        logger.error("新增报修记录失败，报修内容：{}", userRepair.getRepairContent());
        return ResultUtils.error("报修失败!");
    }

    /**
     * 编辑
     */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:myRepair:edit')" + "||  hasAuthority('sys:repairList:do')")
    public ResultVo edit(@RequestBody UserRepair userRepair) {
        boolean b = userRepairService.updateById(userRepair);
        if (b) {
            logger.info("编辑报修记录成功，报修ID：{}", userRepair.getRepairId());
            return ResultUtils.success("编辑成功!");
        }
        logger.error("编辑报修记录失败，报修ID：{}", userRepair.getRepairId());
        return ResultUtils.error("编辑失败!");
    }

    /**
     * 删除
     */
    @PreAuthorize("hasAuthority('sys:myRepair:delete')")
    @DeleteMapping("/{repairId}")
    public ResultVo delete(@PathVariable("repairId") Long repairId) {
        boolean b = userRepairService.removeById(repairId);
        if (b) {
            logger.info("删除报修记录成功，报修ID：{}", repairId);
            return ResultUtils.success("删除成功!");
        }
        logger.error("删除报修记录失败，报修ID：{}", repairId);
        return ResultUtils.error("删除失败!");
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/batch")
    @PreAuthorize("hasAuthority('sys:myRepair:delete')")
    public ResultVo batchDelete(@RequestBody List<Long> repairIds) {
        boolean b = userRepairService.removeByIds(repairIds);
        if (b) {
            logger.info("批量删除报修记录成功，报修ID列表：{}", repairIds);
            return ResultUtils.success("批量删除成功!");
        }
        logger.error("批量删除报修记录失败，报修ID列表：{}", repairIds);
        return ResultUtils.error("批量删除失败!");
    }

    /**
     * 更新报修状态
     */
    @PutMapping("/updateStatus")
    @PreAuthorize("hasAuthority('sys:repairList:do')")
    public ResultVo updateStatus(@RequestBody UserRepair userRepair) {
        UserRepair repair = userRepairService.getById(userRepair.getRepairId());
        if (repair == null) {
            return ResultUtils.error("报修记录不存在!");
        }
        repair.setStatus(userRepair.getStatus());
        boolean b = userRepairService.updateById(repair);
        if (b) {
            logger.info("更新报修状态成功，报修ID：{}，新状态：{}", userRepair.getRepairId(), userRepair.getStatus());
            return ResultUtils.success("状态更新成功!");
        }
        logger.error("更新报修状态失败，报修ID：{}", userRepair.getRepairId());
        return ResultUtils.error("状态更新失败!");
    }

    /**
     * 查询报修详情
     */
    @GetMapping("/{repairId}")
    public ResultVo getDetail(@PathVariable("repairId") Long repairId) {
        UserRepair repair = userRepairService.getById(repairId);
        if (repair == null) {
            return ResultUtils.error("报修记录不存在!");
        }
        return ResultUtils.success("查询成功", repair);
    }
}
